<!-- StrategyList.svelte -->
<script lang="ts">
	import type { PageLoad } from './$types'
	import { goto } from '$app/navigation'
	import * as commands from '$lib/commands'
	import {
		Tabs,
		TabItem,
		Tooltip,
		Table,
		TableBody,
		TableBodyCell,
		TableBodyRow,
		TableHead,
		TableHeadCell,
		TableSearch,
	} from 'flowbite-svelte'
	import {
		UserCircleSolid,
		GridSolid,
		AdjustmentsVerticalSolid,
		ClipboardSolid,
	} from 'flowbite-svelte-icons'
	import type { IpcResponse, TradeBot, UpdateParams, FudaRecord } from '$lib/bindings'

	export let data: PageData
	let searchTerm = ''
	// 如果需要在组件内部生成数据，可以移除上面的export语句并添加以下代码：
	// const generateSampleStrategy = ... // 保持之前的generateSampleStrategy函数定义
	//
	// const tbots = [];
	// for (let i = 1; i <= 100; i++) {
	//   tbots.push(generateSampleStrategy(i));
	// }

	let hoveredRowIndex: number | null = null

	function handleRowHover(index: number) {
		hoveredRowIndex = index
	}

	function handleRowUnhover() {
		hoveredRowIndex = null
	}

	async function handleStartStopClick(
		e: MouseEvent & { currentTarget: EventTarget & HTMLTableRowElement },
		tbot: TradeBot,
	) {
		e.stopPropagation()
		console.log('handleStartStopClick tbot=', tbot, ' tbot.id?.id.String=', tbot.id?.id.String)

		let is_running = false
		if (tbot.is_running) {
			is_running = false
		} else {
			is_running = true
		}
		try {
			// Define the argument
			const args: UpdateParams<TradeBot> = {
				id: tbot.id?.id.String, // "Tstg.DAY.0",
				data: {
					is_running: is_running,
				},
			}

			const res: IpcResponse<FudaRecord> = await commands.update_trade_bot(args)

			console.log('(tbots/+page.ts) res=', res, ' args=', args)

			if (res.error) {
				// If the response status is not OK, throw an error
				throw new Error(`(tbots/+page.ts) Server returned an error: ${res.error}`)
			}
		} catch (e) {
			console.log(e)
		}
	}

	function click_row(
		e: MouseEvent & { currentTarget: EventTarget & HTMLTableRowElement },
		tbot: TradeBot,
	): any {
		let target = e.target as Element
		if (target.closest('button') || target.closest('a')) return // If the click was originated from a button, do nothing (or handle accordingly)

		goto(`/tbots/${tbot.id?.id.String}`)
	}

	function goToPage(page: number) {
		goto(`/tbots/|?page=${page + 1}`)
	}
</script>

<div class="bg-gray-200 w-full h-svh overflow-y-auto">
	<Tabs style="underline" contentClass="p-0 bg-gray-50  dark:bg-gray-800 mt-0">
		<TabItem open>
			<div slot="title" class="flex items-center gap-2">
				<UserCircleSolid size="sm" /><Tooltip>Tooltip content</Tooltip>
				All TBots
			</div>
			<div class="overflow-auto w-full h-full flex flex-col">
				<div class="flex px-4 py-1">
					{#if data.currentPage > 0}
						<button
							on:click={() => goToPage(data.currentPage - 1)}
							class="px-2 uppercase bg-blue-400"
						>
							Prev
						</button>
					{:else}
						<button class="px-2 uppercase bg-gray-400"> Prev </button>
					{/if}

					<button
						on:click={() => goToPage(data.currentPage + 1)}
						class="px-2 uppercase bg-red-400 mx-8"
					>
						Next
					</button>

					<button
						on:click={() => goToPage(data.currentPage + 1)}
						class="px-2 uppercase bg-green-400"
					>
						Back Test
					</button>
				</div>
				<TableSearch
					placeholder="Search by maker name"
					hoverable={true}
					bind:inputValue={searchTerm}
				>
					<tr class="bg-gray-400 text-center font-medium text-gray-900 uppercase sticky top-0 z-10">
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="5"></TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="7">运行收益</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="2">累计盈利</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="2">累计买入</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="2">累计卖出</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap" colspan="2">最新</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">Last Back</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap"></TableHeadCell>
					</tr>
					<tr class="bg-gray-400 text-center font-medium text-gray-900 uppercase sticky top-0 z-10">
						<TableHeadCell padding="pr-2" class="text-nowrap sticky left-0 top-0 bg-gray-400">
							证券代码
						</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">证券名称</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">策略编号</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">策略名称</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">策略K线</TableHeadCell>

						<TableHeadCell padding="pr-2" class="text-nowrap">本周</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">本月</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">季度</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">半年内</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">1年内</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">3年内</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">5年内</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">金额￥</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">盈率</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">金额￥</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">次数</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">金额￥</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">次数</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">买入￥</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">卖出￥</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">Tested</TableHeadCell>
						<TableHeadCell padding="pr-2" class="text-nowrap">Ops</TableHeadCell>
					</tr>
					<TableBody tableBodyClass="divide-y divide-slate-200">
						{#each data.tbots as tbot, index (tbot.id)}
							<TableBodyRow
								class=" hover:bg-green-400"
								tabindex={index}
								on:mouseover={() => handleRowHover(index)}
								on:focus={() => handleRowHover(index)}
								on:mouseout={() => handleRowUnhover()}
								on:blur={() => handleRowUnhover()}
								on:click={(e) => click_row(e, tbot)}
							>
								<TableBodyCell>{tbot.security_symbol}</TableBodyCell>
								<TableBodyCell>{tbot.security_name}</TableBodyCell>
								<TableBodyCell>{tbot.strategy_id?.id.String}</TableBodyCell>
								<TableBodyCell>{tbot.strategy_name}</TableBodyCell>
								<TableBodyCell>{tbot.klt}</TableBodyCell>
								<TableBodyCell>{tbot.avgYield}</TableBodyCell>
								<TableBodyCell>{tbot.maxYield}</TableBodyCell>
								<TableBodyCell>{tbot.minYield}</TableBodyCell>
								<TableBodyCell>{tbot.minYield}</TableBodyCell>
								<TableBodyCell>{tbot.minYield}</TableBodyCell>
								<TableBodyCell>{tbot.minYield}</TableBodyCell>
								<TableBodyCell>{tbot.minYield}</TableBodyCell>
								<TableBodyCell>188,896</TableBodyCell>
								<TableBodyCell>24%</TableBodyCell>
								<TableBodyCell>5000</TableBodyCell>
								<TableBodyCell>30</TableBodyCell>
								<TableBodyCell>8896</TableBodyCell>
								<TableBodyCell>20</TableBodyCell>
								<TableBodyCell>5000(3d)</TableBodyCell>
								<TableBodyCell>8896(3w)</TableBodyCell>
								<TableBodyCell>3分钟前</TableBodyCell>
								<TableBodyCell>
									{#if tbot.is_running}
										<button
											on:click={(e) => handleStartStopClick(e, tbot)}
											class="flex-none border-collapse border-solid border-2 bg-red-400 px-2 uppercase"
										>
											Stop
										</button>
									{:else}
										<button
											on:click={(e) => handleStartStopClick(e, tbot)}
											class="flex-none border-collapse border-solid border-2 bg-green-400 px-2 uppercase"
										>
											Start
										</button>
									{/if}
								</TableBodyCell>
							</TableBodyRow>
						{/each}
						<TableBodyRow>
							<TableBodyCell colspan="21">Bottom Line-----</TableBodyCell>
						</TableBodyRow>
					</TableBody>
				</TableSearch>
			</div>
		</TabItem>
		<TabItem>
			<div slot="title" class="flex items-center gap-2">
				<GridSolid size="sm" /><Tooltip>Tooltip content</Tooltip>
				Running TBots
			</div>
			<p class="text-sm text-gray-500 dark:text-gray-400">
				<b>Running TBots:</b>
				{#each Array.from({ length: 60 }, (_, i) => i) as number}
					Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
					ut labore et dolore magna aliqua. {number}<br />
				{/each}
			</p>
		</TabItem>

		<TabItem>
			<div slot="title" class="flex items-center gap-2">
				<GridSolid size="sm" /><Tooltip>T-Bots Halted: An Overview of the Situation</Tooltip>
				Stopped TBots
			</div>
			<p class="text-sm text-gray-500 dark:text-gray-400">
				<b>Stopped TBots:</b>
				{#each Array.from({ length: 60 }, (_, i) => i) as number}
					Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
					ut labore et dolore magna aliqua. {number}<br />
				{/each}
			</p>
		</TabItem>

		<TabItem>
			<div slot="title" class="flex items-center gap-2">
				<GridSolid size="sm" />
				Dashboard
			</div>
			<p class="text-sm text-gray-500 dark:text-gray-400 max-h-48">
				<b>Dashboard:</b>
				{#each Array.from({ length: 30 }, (_, i) => i) as number}
					Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
					ut labore et dolore magna aliqua. {number}<br />
				{/each}
			</p>
		</TabItem>
	</Tabs>
</div>
